package com.huizhonglm.diap.ui.wallet;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bruce.common.utils.EmptyUtil;
import com.bruce.common.utils.FileUtil;
import com.huizhonglm.diap.R;
import com.huizhonglm.diap.api.API;
import com.huizhonglm.diap.api.CommonParams;
import com.huizhonglm.diap.api.CommonResponse;
import com.huizhonglm.diap.api.HttpCallback;
import com.huizhonglm.diap.api.Status;
import com.huizhonglm.diap.api.model.wallet.BankCardInfo;
import com.huizhonglm.diap.api.model.wallet.BankCardRemParams;
import com.huizhonglm.diap.api.model.wallet.CheckTPWDParams;
import com.huizhonglm.diap.api.model.wallet.IsSettedResponse;
import com.huizhonglm.diap.core.utils.DialogUtil;
import com.huizhonglm.diap.core.utils.TPWDUtil;
import com.huizhonglm.diap.core.utils.ToastUtil;
import com.huizhonglm.diap.core.utils.UserUtil;
import com.huizhonglm.diap.presenters.wallet.BankCardListPersenter;
import com.huizhonglm.diap.ui.BaseActivity;
import com.huizhonglm.diap.ui.user.FinishUserInfoActivity;
import com.huizhonglm.diap.ui.wallet.iView.BankCardListIView;
import com.huizhonglm.diap.widget.LoadView;

import java.util.ArrayList;
import java.util.List;

/**
 * 银行卡列表
 *
 * @author LiXiaoLong
 * @version 1.0
 * @since 2016-03-22 14:02
 */
public class BankCardListActivty extends BaseActivity implements BankCardListIView,
        LoadView.OnLoadAgainListener, AdapterView.OnItemLongClickListener {

    private Context mContext;

    private LoadView mLoadView;
    private ListView mListView;

    private BankCardListAdapter mAdapter;

    private BankCardListPersenter mPresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bank_card_list);
        setBackEvent(this, null);
        mContext = BankCardListActivty.this;
        mPresenter = new BankCardListPersenter(this);
        assignViews();
    }

    @Override
    protected void assignViews() {
        View scrlView = findViewById(R.id.bank_card_scrl);
        mLoadView = (LoadView) findViewById(R.id.load_view);
        mListView = (ListView) findViewById(R.id.bank_card_list);
        TextView addCardBtn = (TextView) findViewById(R.id.add_card_txt);
        mLoadView.setDataView(scrlView, this);
        mListView.setOnItemLongClickListener(this);
        addCardBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showProgressBar();
                checkSetTPWD();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        onLoadAgain();
    }

    @Override
    public void onLoadAgain() {
        mLoadView.showProgress();
        mPresenter.loadBankCards();
    }

    @Override
    public void onLoadCardsSuccess(List<BankCardInfo> data) {
        if (EmptyUtil.isEmpty(data)) {
            data = new ArrayList<>();
        }
        if (mAdapter == null) {
            mAdapter = new BankCardListAdapter(mContext, data);
            mListView.setAdapter(mAdapter);
        } else {
            mAdapter.setData(data);
            mAdapter.notifyDataSetChanged();
        }
        mLoadView.showDataView();
    }

    @Override
    public void onLoadCardsFailure() {
        mLoadView.showErrorView();
    }

    public void unBindedCardSuccess() {
        hideProgressBar();
        ToastUtil.makeTextShort("银行卡解绑成功");
        onLoadAgain();
    }

    public void unBindedCardFailure() {
        hideProgressBar();
        ToastUtil.makeTextShort("银行卡解绑失败");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            onLoadAgain();
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        final BankCardInfo info = mAdapter.getItem(position);
        if (info != null) {
            DialogUtil.showNormalDialog(mContext, "解绑银行卡", "您确定要解绑此银行卡吗？", "取消", "解绑", new DialogUtil.OnDialogBtnClickListener(){

                @Override
                public void onBtnClick(String btnText) {
                    if ("解绑".equals(btnText)) {
                        showProgressBar();
                        unbindedCard(info.getCbaId());
                    }
                }
            });
        }

        return true;
    }

    public void unbindedCard(String cardId){
        BankCardRemParams params = new BankCardRemParams();
        params.bindedCardId = cardId;
        API.http().post("unbindedCard", params, new HttpCallback() {
            @Override
            public void onSuccess(String result) {
                CommonResponse resp = JSON.parseObject(result, CommonResponse.class);
                if (resp != null && Status.SUCCESS.equals(resp.getStatus())){
                    unBindedCardSuccess();
                } else {
                    unBindedCardFailure();
                }
            }

            @Override
            public void onFailure(Throwable ex) {
                unBindedCardFailure();
            }
        });
    }

    public void checkSetTPWD() {
        API.http().post("checkSetTPWD", new CommonParams(API.CHK_SET_TPWD), new HttpCallback() {
            @Override
            public void onSuccess(String result) {
                if (!EmptyUtil.isEmpty(result)) {
                    IsSettedResponse resp = JSON.parseObject(result, IsSettedResponse.class);
                    if (resp != null){
                        if ("Y".equals(resp.getIsSetted())){
                            hideProgressBar();
                            showTPWDInputDialog();
                        } else {
                            checkSetUserInfo();
                        }
                    } else {
                        hideProgressBar();
                        ToastUtil.makeTextShort("服务异常，请稍后重试");
                    }
                } else {
                    hideProgressBar();
                    ToastUtil.makeTextShort("服务异常，请稍后重试");
                }
            }

            @Override
            public void onFailure(Throwable ex) {
                hideProgressBar();
                ToastUtil.makeTextShort("服务异常，请稍后重试");
            }
        });
    }

    public void checkSetUserInfo() {
        API.http().post("checkSetUserInfo", new CommonParams(API.CHK_SET_USER_INFO), new HttpCallback() {
            @Override
            public void onSuccess(String result) {
                hideProgressBar();
                if (!EmptyUtil.isEmpty(result)) {
                    IsSettedResponse resp = JSON.parseObject(result, IsSettedResponse.class);
                    if (resp != null){
                        if ("Y".equals(resp.getIsSetted())){
                            // 设置交易密码
                            startActivity(new Intent(BankCardListActivty.this, TPWDSettingActivity.class));
                        } else {
                            // 完善资料
                            startActivity(new Intent(BankCardListActivty.this, FinishUserInfoActivity.class));
                        }
                    } else {
                        ToastUtil.makeTextShort("服务异常，请稍后重试");
                    }
                } else {
                    ToastUtil.makeTextShort("服务异常，请稍后重试");
                }
            }

            @Override
            public void onFailure(Throwable ex) {
                ToastUtil.makeTextShort("服务异常，请稍后重试");
            }
        });
    }

    public void checkTPWD(String passwd){
        CheckTPWDParams params = new CheckTPWDParams();
        params.userId = UserUtil.getUserId();
        params.password = FileUtil.MD5(passwd);
        API.http().post("checkTPWD", params, new HttpCallback() {
            @Override
            public void onSuccess(String result) {
                if (!EmptyUtil.isEmpty(result)) {
                    CommonResponse resp = JSON.parseObject(result, CommonResponse.class);
                    if (resp != null){
                        if (Status.SUCCESS.equals(resp.getStatus())){
                            // 添加新银行卡
                            Intent intent = new Intent(mContext, BankCardAddActivity.class);
                            startActivityForResult(intent, 0);
                        } else {
                            ToastUtil.makeTextShort("交易密码错误");
                        }
                    } else {
                        ToastUtil.makeTextShort("交易密码错误");
                    }
                } else {
                    ToastUtil.makeTextShort("交易密码错误");
                }
            }

            @Override
            public void onFailure(Throwable ex) {
                ToastUtil.makeTextShort("服务异常，请稍后重试");
            }
        });
    }

    private TPWDUtil tpwdUtil;

    private void showTPWDInputDialog() {
        if (tpwdUtil == null) {
            tpwdUtil = new TPWDUtil(BankCardListActivty.this, new TPWDUtil.OnInputCompleteListener() {
                @Override
                public void onInputCompleted(String tpwd) {
                    checkTPWD(tpwd);
                }
            });
        }
        tpwdUtil.showDialog();
    }


}